// 实时更新时间
function updateTime() {
    const now = new Date();
    const timeStr = now.toLocaleTimeString('zh-CN', {hour12: false});
    const dateStr = now.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
    });

    document.getElementById('current-time').textContent = timeStr;
    document.getElementById('current-date').textContent = dateStr;
}

setInterval(updateTime, 1000);
updateTime();

// 初始化所有图表
function initCharts(data) {
    // 1. 手术数量趋势折线图
    const surgeryChart = echarts.init(document.getElementById('surgery-trend-chart'));

    // 处理手术趋势数据（后端返回数组）
    const surgeryYears = data.surgeryTrend.map(item => item.year);
    const scheduledData = data.surgeryTrend.map(item => item.Scheduled);
    const completedData = data.surgeryTrend.map(item => item.Completed);
    const cancelledData = data.surgeryTrend.map(item => item.Cancelled);

    const surgeryOption = {
        tooltip: { trigger: 'axis' },
        legend: {
            data: ['预约手术', '已完成', '已取消'],
            textStyle: { color: '#a0d0ff' },
            bottom: 0
        },
        grid: { top: '10%', left: '3%', right: '4%', bottom: '15%', containLabel: true },
        xAxis: {
            type: 'category',
            data: surgeryYears,
            axisLine: { lineStyle: { color: '#3a6a99' } },
            axisLabel: { color: '#a0d0ff', fontSize: 11 }
        },
        yAxis: {
            type: 'value',
            axisLine: { show: true, lineStyle: { color: '#3a6a99' } },
            axisLabel: { color: '#a0d0ff', fontSize: 11 },
            splitLine: { lineStyle: { color: 'rgba(58, 106, 153, 0.3)' } }
        },
        series: [
            {
                name: '预约手术',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 6,
                lineStyle: { width: 2, color: '#409eff' },
                itemStyle: { color: '#409eff' },
                data: scheduledData
            },
            {
                name: '已完成',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 6,
                lineStyle: { width: 2, color: '#4caf50' },
                itemStyle: { color: '#4caf50' },
                data: completedData
            },
            {
                name: '已取消',
                type: 'line',
                smooth: true,
                symbol: 'circle',
                symbolSize: 6,
                lineStyle: { width: 2, color: '#f44336' },
                itemStyle: { color: '#f44336' },
                data: cancelledData
            }
        ]
    };
    surgeryChart.setOption(surgeryOption);

    // 2. 当月出院环比饼图
    const dischargeChart = echarts.init(document.getElementById('discharge-chart'));
    const dischargeOption = {
        tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
        legend: {
            orient: 'horizontal',
            bottom: 0,
            textStyle: { color: '#a0d0ff', fontSize: 11 },
            data: ['入院', '出院', '留院']
        },
        series: [{
            name: '出院环比',
            type: 'pie',
            radius: ['40%', '65%'],
            avoidLabelOverlap: false,
            itemStyle: {
                borderRadius: 8,
                borderColor: '#0c1b2a',
                borderWidth: 2
            },
            label: {
                show: true,
                formatter: '{b}: {c}',
                color: '#e0f0ff',
                fontSize: 11
            },
            emphasis: {
                label: { show: true, fontSize: 12, fontWeight: 'bold' },
                itemStyle: { shadowBlur: 8, shadowColor: 'rgba(0, 0, 0, 0.5)' }
            },
            data: [
                { value: data.dischargeData.admission, name: '入院', itemStyle: { color: '#409eff' } },
                { value: data.dischargeData.discharge, name: '出院', itemStyle: { color: '#4caf50' } },
                { value: data.dischargeData.retained, name: '留院', itemStyle: { color: '#f44336' } }
            ]
        }]
    };
    dischargeChart.setOption(dischargeOption);

    // 3. 病症诊断人数柱状图
    const diseaseChart = echarts.init(document.getElementById('disease-chart'));
    const diseaseNames = data.diseaseData.map(item => item.name);
    const paidData = data.diseaseData.map(item => item.paid);
    const unpaidData = data.diseaseData.map(item => item.unpaid);

    const diseaseOption = {
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        legend: {
            data: ['已付款', '未结算'],
            textStyle: { color: '#a0d0ff', fontSize: 11 },
            bottom: 0
        },
        grid: { left: '3%', right: '4%', bottom: '15%', top: '10%', containLabel: true },
        xAxis: {
            type: 'category',
            data: diseaseNames,
            axisLine: { lineStyle: { color: '#3a6a99' } },
            axisLabel: {
                color: '#a0d0ff',
                interval: 0,
                rotate: 30,
                fontSize: 11
            }
        },
        yAxis: {
            type: 'value',
            axisLine: { show: true, lineStyle: { color: '#3a6a99' } },
            axisLabel: { color: '#a0d0ff', fontSize: 11 },
            splitLine: { lineStyle: { color: 'rgba(58, 106, 153, 0.3)' } }
        },
        series: [
            {
                name: '已付款',
                type: 'bar',
                stack: 'total',
                barWidth: '35%',
                itemStyle: { color: '#4caf50' },
                data: paidData
            },
            {
                name: '未结算',
                type: 'bar',
                stack: 'total',
                barWidth: '35%',
                itemStyle: { color: '#f44336' },
                data: unpaidData
            }
        ]
    };
    diseaseChart.setOption(diseaseOption);

    // 4. 年龄分布饼图（后端返回数组，转换为对象）
    const ageChart = echarts.init(document.getElementById('age-chart'));

    // 将数组转换为对象格式
    const ageDistributionObj = {};
    data.ageDistribution.forEach(item => {
        ageDistributionObj[item.age_group] = item.count;
    });

    const ageData = Object.entries(ageDistributionObj).map(([name, value]) => {
        const colors = {
            '0-18岁': '#64b5f6',
            '19-35岁': '#4caf50',
            '36-50岁': '#ff9800',
            '51-65岁': '#f44336',
            '65岁以上': '#9c27b0'
        };
        return {
            value: value,
            name: name,
            itemStyle: { color: colors[name] }
        };
    });

    const ageOption = {
        tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
        legend: {
            orient: 'vertical',
            right: 10,
            top: 'center',
            textStyle: { color: '#a0d0ff', fontSize: 11 },
            data: Object.keys(ageDistributionObj)
        },
        series: [{
            name: '年龄分布',
            type: 'pie',
            radius: ['40%', '65%'],
            center: ['40%', '50%'],
            roseType: 'area',
            itemStyle: {
                borderRadius: 6,
                borderColor: '#0c1b2a',
                borderWidth: 2
            },
            label: { color: '#e0f0ff', fontSize: 11 },
            data: ageData
        }]
    };
    ageChart.setOption(ageOption);

    // 5. 人均医药费分布雷达图
    const costChart = echarts.init(document.getElementById('cost-chart'));
    const costIndicator = data.costDistribution.map(item => ({
        name: item.range,
        max: Math.max(1500, Math.ceil(item.count * 1.2))
    }));
    const costValues = data.costDistribution.map(item => item.count);

    const costOption = {
        tooltip: { trigger: 'item' },
        radar: {
            indicator: costIndicator,
            shape: 'circle',
            splitArea: { show: false },
            axisName: {
                color: '#a0d0ff',
                backgroundColor: '#0c1b2a',
                borderRadius: 3,
                padding: [3, 5],
                fontSize: 11
            },
            axisLine: { lineStyle: { color: 'rgba(58, 106, 153, 0.5)' } },
            splitLine: { lineStyle: { color: 'rgba(58, 106, 153, 0.3)' } }
        },
        series: [{
            name: '人均医药费分布',
            type: 'radar',
            symbolSize: 6,
            areaStyle: { color: 'rgba(64, 158, 255, 0.3)' },
            lineStyle: { width: 2, color: '#409eff' },
            data: [{
                value: costValues,
                name: '分布人数',
                symbol: 'circle',
                itemStyle: { color: '#409eff' },
                label: { show: true, formatter: '{c}', color: '#e0f0ff', fontSize: 11 }
            }]
        }]
    };
    costChart.setOption(costOption);

    // 6. 付费方式分布饼图（后端返回数组，转换为对象）
    const paymentChart = echarts.init(document.getElementById('payment-chart'));

    // 将数组转换为对象格式
    const paymentDistributionObj = {};
    data.paymentDistribution.forEach(item => {
        paymentDistributionObj[item.payment_method] = item.count;
    });

    const paymentData = Object.entries(paymentDistributionObj).map(([name, value]) => {
        const colors = {
            '支付宝': '#1677ff',
            '银行卡': '#13c2c2',
            '医保卡': '#52c41a',
            '微信': '#2f54eb'
        };
        return {
            value: value,
            name: name,
            itemStyle: { color: colors[name] }
        };
    });

    const paymentOption = {
        tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
        legend: {
            orient: 'horizontal',
            bottom: 0,
            textStyle: { color: '#a0d0ff', fontSize: 11 },
            data: Object.keys(paymentDistributionObj)
        },
        series: [{
            name: '付费方式',
            type: 'pie',
            radius: ['30%', '55%'],
            center: ['50%', '45%'],
            itemStyle: {
                borderRadius: 8,
                borderColor: '#0c1b2a',
                borderWidth: 2
            },
            label: { color: '#e0f0ff', fontSize: 11 },
            data: paymentData
        }]
    };
    paymentChart.setOption(paymentOption);
}

// 初始化人次占比卡片
function initVisitCards(visitData) {
    const container = document.getElementById('visit-container');
    container.innerHTML = '';

    visitData.forEach(item => {
        const change = item.today - item.yesterday;
        const changePercent = Math.round((change / (item.yesterday || 1)) * 100); // 防止除以0

        const visitItem = document.createElement('div');
        visitItem.className = 'visit-item';
        visitItem.innerHTML = `
                    <div class="visit-type">${item.type}</div>
                    <div class="visit-value">${item.today}</div>
                    <div class="visit-change">
                        <span class="${change >= 0 ? 'up' : 'down'}">
                            ${change >= 0 ? '↑' : '↓'} ${Math.abs(change)} (${Math.abs(changePercent)}%)
                        </span>
                    </div>
                    <div class="visit-proportion">占比: ${item.proportion}%</div>
                `;

        container.appendChild(visitItem);
    });
}

// 初始化医疗耗材环比卡片（后端返回数组）
function initSupplyCards(suppliesRatio) {
    const container = document.getElementById('supply-card');
    container.innerHTML = '';

    // 从数组中提取医药数据
    const medicalData = suppliesRatio.find(item => item.category === "medical");
    // 从数组中提取耗材数据
    const suppliesData = suppliesRatio.find(item => item.category === "supplies");

    // 医药环比卡片
    if (medicalData) {
        const medicalChange = medicalData.current - medicalData.lastMonth;
        // 防止除以0
        const medicalChangePercent = medicalData.lastMonth === 0 ? 100 :
            Math.round((medicalChange / medicalData.lastMonth) * 100);

        const medicalItem = document.createElement('div');
        medicalItem.className = 'supply-item';
        medicalItem.innerHTML = `
                <div class="supply-label">医药</div>
                <div class="supply-value">${medicalData.current}</div>
                <div class="supply-change ${medicalChange >= 0 ? 'up' : 'down'}">
                    ${medicalChange >= 0 ? '↑' : '↓'} ${Math.abs(medicalChange)} (${Math.abs(medicalChangePercent)}%)
                </div>
                <div class="supply-subtext">上月: ${medicalData.lastMonth}</div>
            `;

        container.appendChild(medicalItem);
    }

    // 耗材环比卡片
    if (suppliesData) {
        const suppliesChange = suppliesData.current - suppliesData.lastMonth;
        // 防止除以0
        const suppliesChangePercent = suppliesData.lastMonth === 0 ? 100 :
            Math.round((suppliesChange / suppliesData.lastMonth) * 100);

        const suppliesItem = document.createElement('div');
        suppliesItem.className = 'supply-item';
        suppliesItem.innerHTML = `
                <div class="supply-label">耗材</div>
                <div class="supply-value">${suppliesData.current}</div>
                <div class="supply-change ${suppliesChange >= 0 ? 'up' : 'down'}">
                    ${suppliesChange >= 0 ? '↑' : '↓'} ${Math.abs(suppliesChange)} (${Math.abs(suppliesChangePercent)}%)
                </div>
                <div class="supply-subtext">上月: ${suppliesData.lastMonth}</div>
            `;

        container.appendChild(suppliesItem);
    }
}

function initSharedTable(sharedData) {
    const container = document.getElementById('shared-scroll-container');
    container.innerHTML = '';

    // 创建滚动内容容器
    const scrollContent = document.createElement('div');
    scrollContent.className = 'scroll-content';
    container.appendChild(scrollContent);

    // 渲染所有数据行
    sharedData.forEach((item, index) => {
        const row = document.createElement('div');
        row.className = 'scroll-item';
        row.innerHTML = `
                <div>${item.hospital}</div>
                <div>${item.department}</div>
                <div>${item.shared}</div>
            `;
        scrollContent.appendChild(row);
    });

    // 创建滚动控制区域
    const scrollControls = document.createElement('div');
    scrollControls.className = 'scroll-controls';
    scrollControls.innerHTML = '<div id="scroll-status">自动滚动中 <span class="icon">▶</span></div>';
    container.appendChild(scrollControls);

    // 计算行高
    const rowHeight = scrollContent.firstChild ? scrollContent.firstChild.offsetHeight : 48;

    // 计算最大可见行数（根据容器高度动态计算）
    const visibleRows = Math.floor((container.clientHeight - 46) / rowHeight);

    // 滚动状态控制
    let currentPosition = 0;
    let isPaused = false;
    let animationId = null;
    const scrollDuration = 500; // 滚动动画时间

    // 获取滚动状态元素
    const scrollStatus = document.getElementById('scroll-status');

    // 添加滚动控制点击事件
    if (scrollStatus) {
        scrollStatus.addEventListener('click', togglePause);
    }

    // 添加手动滚动功能
    container.addEventListener('wheel', function(e) {
        // 检测到手动滚动时暂停自动滚动
        if (!isPaused) {
            togglePause();
        }

        // 阻止默认滚动行为，改用自定义滚动
        e.preventDefault();
        const direction = e.deltaY > 0 ? 1 : -1;
        scrollTo(currentPosition + direction);
    });
    function togglePause() {
        isPaused = !isPaused;
        scrollStatus.classList.toggle('paused', isPaused);
        scrollStatus.innerHTML = isPaused ?
            '已暂停 <span class="icon">▶</span>' :
            '自动滚动中 <span class="icon">▶</span>';

        if (!isPaused && !animationId) {
            startScrolling();
        } else if (isPaused) {
            cancelAnimationFrame(animationId);
            animationId = null;
        }
    }

    // 平滑滚动函数
    function scrollTo(position) {
        // 边界检查
        position = Math.max(0, Math.min(position, sharedData.length - visibleRows));

        // 创建平滑滚动动画
        cancelAnimationFrame(animationId);

        const startPosition = currentPosition;
        const startTime = performance.now();

        function animateScroll(currentTime) {
            const elapsed = currentTime - startTime;
            const progress = Math.min(elapsed / scrollDuration, 1);

            // 使用缓动函数使滚动更自然
            const easeProgress = easeOutCubic(progress);
            const scrollY = (startPosition + (position - startPosition) * easeProgress) * rowHeight;

            scrollContent.style.transform = `translateY(-${scrollY}px)`;

            if (progress < 1) {
                animationId = requestAnimationFrame(animateScroll);
            } else {
                currentPosition = position;
                animationId = null;
            }
        }

        animationId = requestAnimationFrame(animateScroll);
    }

    // 缓动函数 - 创造更自然的滚动效果
    function easeOutCubic(t) {
        return 1 - Math.pow(1 - t, 3);
    }

    // 自动滚动到下一项
    function scrollToNext() {
        if (isPaused) return;

        let nextPosition = currentPosition + 1;

        if (nextPosition > sharedData.length - visibleRows) {
            // 平滑滚动回顶部
            nextPosition = 0;
        }

        scrollTo(nextPosition);
    }

    // 启动自动滚动
    function startScrolling() {
        cancelAnimationFrame(animationId);

        // 设置定时器进行自动滚动
        setTimeout(() => {
            let scrollTimer = null;

            function autoScroll() {
                scrollToNext();

                if (!isPaused) {
                    scrollTimer = setTimeout(autoScroll, 3000); // 每3秒滚动一次
                }
            }

            autoScroll();

            // 保存timer以便后续清除
            window.scrollTimer = scrollTimer;
        }, 1000); // 初始等待时间
    }

    // 开始滚动
    startScrolling();
}

// 窗口大小变化时重置图表大小
window.addEventListener('resize', function() {
    echarts.getInstanceByDom(document.getElementById('surgery-trend-chart'))?.resize();
    echarts.getInstanceByDom(document.getElementById('discharge-chart'))?.resize();
    echarts.getInstanceByDom(document.getElementById('disease-chart'))?.resize();
    echarts.getInstanceByDom(document.getElementById('age-chart'))?.resize();
    echarts.getInstanceByDom(document.getElementById('cost-chart'))?.resize();
    echarts.getInstanceByDom(document.getElementById('payment-chart'))?.resize();
});

// 模拟从后端获取数据并初始化仪表板
function fetchDataAndInit() {
    // 使用 fetch API 从后端获取数据
    fetch('/api/dashboard/data')
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应异常');
            }
            return response.json();
        })
        .then(data => {
            // 初始化所有组件
            initCharts(data);
            initVisitCards(data.visitData);
            initSupplyCards(data.suppliesRatio);
            initSharedTable(data.sharedData);
        })
        .catch(error => {
            console.error('获取数据失败:', error);

            // 显示错误信息
            const errorElements = document.querySelectorAll('.loading');
            errorElements.forEach(el => {
                el.innerHTML = '<div style="color: #f44336;">数据加载失败，请刷新页面重试</div>';
            });
        });
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', fetchDataAndInit);